<html>
	<head>
		<script src="../../src/gears_init.js"></script>
		<script src="../../src/Norm.js"></script>
		<script src="../../src/Norm.Logger.Gears.js"></script>
		<script src="../../src/Norm.Database.Gears.js"></script>
		<script src="../../src/Norm.ResultIterator.Gears.js"></script>
		<script src="../../src/Norm.LastIdManager.js"></script>
		<script src="../../src/Norm.Events.js"></script>
		<script src="../../src/Norm.Sql.js"></script>
		<script src="../../src/Norm.Fields.js"></script>
		<script src="../../src/Norm.Model.js"></script>
		<script src="../../src/Norm.Introspection.js"></script>
		<script src="../../src/Norm.Transaction.js"></script>
		<script>
			Norm.Database.name = "test.m2m";
			var Tag = new Norm.Model({
				name : "Tag",
				fields : {
					name : new Norm.Fields.String({maxLength : 20}),
					posts : new Norm.Fields.ManyToMany({related : "Post"})
				}
			});
			
			var Post = new Norm.Model({
				name : "Post",
				fields : {
					title : new Norm.Fields.String({maxLength : 50}),
					body : new Norm.Fields.String({maxLength : 5000}),
					tags : new Norm.Fields.ManyToMany({related : "Tag"})
				}
			});
			
			var Tests = {
				
				up : function() {
					
					Post.dropTable();
					Tag.dropTable();
					Post.createTable();
					Tag.createTable();
					new Post({title : "test post", body : "test body"}).save();
					new Tag({name : "test tag"}).save();
				},
				
				"test if select works with ManyToMany relation" : function() {
					
					var post = Post.select().getOne();				// create relation Post<=>Tag
					var tag = Tag.select().getOne();
					
					post.tags.add(tag);
					UnitTest.assertTrue(
						post.tags.select().toArray().length == 1 && tag.posts.select().toArray().length == 1,
						"relation between tag<=>post wasn`t created"
					);
				},
				
				"test if remove works with ManyToMany relation" : function()
				{
					var post = Post.select().getOne();
					var tag = Tag.select().getOne();
					post.tags.remove(tag);
					UnitTest.assertTrue(
						post.tags.select().toArray().length == 0 && tag.posts.select().toArray().length == 0,
						"relation between tag<=>post wasn`t deleted"
					);
				},
				
				"test if m2m foreign keys are enforced" : function() {
					var post = Post.select().getOne();
					var newTag = new Tag({name : "test new tag", rowid : 10});
					
					try {
						post.tags.add(newTag);						// insert
					} catch(e) {
						return;
					}
					try {
						post.tags.remove(newTag);					// delete
					} catch(e) {
						return;
					}
					throw new Error("a exception didn`t happen even that the insert or delete vaiolate the foreign key");
				},
				
				down : function() {
					
					Post.dropTable();
					Tag.dropTable();
				}
			};
		</script>
		<script src="unit-test.js"></script>
	</head>
	<body>
		
	</body>
</html>
